<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="java 中有一些方法前面的关键字是native，该关键字修饰的方法表明当前方法不是由 java 实现的方法，而是由本地语言编写的。本地语言就是所在的操作系统所用的语言。因为一些和操作系统底层相关的方法是 java 无法实现的，或者基于性能的考虑，由 java 实现并没有用本地方法实现在执行效率上更高效，所以会用到本地方法。 本地方法的调用是通过 JNI(Java Native Interface">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(17)本地方法的调用过程">
<meta property="og:url" content="https://zachaxy.github.io/2018/01/18/手写JVM系列-17-本地方法的调用过程/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="java 中有一些方法前面的关键字是native，该关键字修饰的方法表明当前方法不是由 java 实现的方法，而是由本地语言编写的。本地语言就是所在的操作系统所用的语言。因为一些和操作系统底层相关的方法是 java 无法实现的，或者基于性能的考虑，由 java 实现并没有用本地方法实现在执行效率上更高效，所以会用到本地方法。 本地方法的调用是通过 JNI(Java Native Interface">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.304Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(17)本地方法的调用过程">
<meta name="twitter:description" content="java 中有一些方法前面的关键字是native，该关键字修饰的方法表明当前方法不是由 java 实现的方法，而是由本地语言编写的。本地语言就是所在的操作系统所用的语言。因为一些和操作系统底层相关的方法是 java 无法实现的，或者基于性能的考虑，由 java 实现并没有用本地方法实现在执行效率上更高效，所以会用到本地方法。 本地方法的调用是通过 JNI(Java Native Interface">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2018/01/18/手写JVM系列-17-本地方法的调用过程/">





  <title>手写JVM系列(17)本地方法的调用过程 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2018/01/18/手写JVM系列-17-本地方法的调用过程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(17)本地方法的调用过程</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-18T22:26:52+08:00">
                2018-01-18
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,879
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <p>java 中有一些方法前面的关键字是<code>native</code>，该关键字修饰的方法表明当前方法不是由 java 实现的方法，而是由本地语言编写的。本地语言就是所在的操作系统所用的语言。因为一些和操作系统底层相关的方法是 java 无法实现的，或者基于性能的考虑，由 java 实现并没有用本地方法实现在执行效率上更高效，所以会用到本地方法。</p>
<p>本地方法的调用是通过 JNI(Java Native Interface)来实现的，JNI 是 JVM 中的一个重要组成部分，但是要让 JVM 支持 JNI 规范还需要做大量的工作，而本系列关于 JVM 的介绍主要还是 JVM 的工作原理，为了不陷入到 JNI 的细节中，同时我们的 JVM 是用 java 来实现的，本身也不具备实现 JNI 规范的能力。因此这里只是通过简单的实例，通过 java 来描述 JNI 的实现过程。本节所实现的代码都在<a href="https://github.com/zachaxy/JVM/tree/master/Java/src/znative" target="_blank" rel="noopener">znative 包下</a><br>有关 JNI 的细节，请参考<a href="https://zachaxy.github.io/tags/JNI/">JNI 系列文章</a></p>
<a id="more"></a>

<h1 id="本地方法的注册"><a href="#本地方法的注册" class="headerlink" title="本地方法的注册"></a>本地方法的注册</h1><p>这里提到了注册，一般说起注册，都是在某处进行登记，表明自身的存在。其实在 JVM 中有一个<strong>本地方法注册表</strong>，native 方法的注册也是起一个标记占坑的作用，在本地方法表中注册本地方法，方便后面 JVM 需要调用本地方法时，能够从本地方法注册表中找到对应的本地方法。本节注册本地方法的代码请参考<a href="https://github.com/zachaxy/JVM/tree/master/Java/src/znative/RegisterCenter.java" target="_blank" rel="noopener">RegisterCenter.java</a></p>
<p>JVM 一般是用 c 语言编写的，在 JVM 的实现中，本地方法其实是在 JVM 中实现的， java 中本地方法都会映射为 JVM 中 c 的一个方法指针。</p>
<p>要实现本地方法的注册，其实就是实现<strong>本地方法注册表</strong>，本地方法注册表本质是上就是一个 map 的数据结构，其 key 为方法所在的类+方法名+方法签名，value 为本地方法的指针。<br>然而我们用 java 实现的 JVM ，所以只能用接口的方式来模拟 c 中的方法指针。<strong>再次强调用 java 来实现 JVM 是不正规的，但是通过本章的介绍，依然可以对 JVM 本地方法的实现有一个整理的理解。</strong><br>用接口的方式模拟 c 中的指针，我们所定义的接口如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">NativeMethod</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(Zframe frame)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>定义 NativeMethod 接口，其接口中只有一个 run 方法，用来执行本地方法，同时该方法需要一个 frame 参数，之前介绍 Frame 时，代表一个方法的工作空间，同样本地方法也需要一个工作空间，该 frame 参数就是当前本地方法的工作空间。</p>
<p>下面是本地方法的注册实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> HashMap&lt;String, NativeMethod&gt; nativeMethods = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(String className, String methodName, String methodDescriptor, NativeMethod nativeMethod)</span> </span>&#123;</span><br><span class="line">    String key = className + <span class="string">"~"</span> + methodName + <span class="string">"~"</span> + methodDescriptor;</span><br><span class="line">    nativeMethods.put(key, nativeMethod);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="本地方法注册的时机"><a href="#本地方法注册的时机" class="headerlink" title="本地方法注册的时机"></a>本地方法注册的时机</h1><p>接下来要考虑的问题在何时进行注册，哪些方法需要注册。其实很多 java 类中都包含 native 方法，而在这些包含 native 方法的类中，一般都有一个 registerNatives 的本地方法，该方法的作用是用来将本类中其它的 native 方法注册到本地方法注册表中。而 registerNatives 方法都是在类的静态代码块中执行的，也就是当前类加载到虚拟机的时候，就将该类的本地方法注册到本地方法注册表中。<br>例如 <code>java.lang.Object</code>中的实现，java 中其它类基本上也是这样的套路。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Object</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">native</span> <span class="keyword">void</span> <span class="title">registerNatives</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        registerNatives();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们的 JVM 只是简易的实现版本，所有的方法都是通过代码手动注册的，所以并没有实现 registerNatives 方法，而是将 Object 中的 native 方法一一手动注册进来。当然可以在遇到 registerNatives 的本地方法时，就将扫描当前类中的 native 方法，依次注册进来。我们的 JVM 就不这样实现了，开篇也也说了我们不想花太多精力在 JNI 的实现细节上，所以我们只是会手动注册有限的几个本地方法，来大致了解一下本地方法调用的整个流程。所以如果遇到了调用 registerNatives 方法的情况，不管其所在的哪个类，就返回一个空的实现。</p>
<p>而我们的 JVM 中所手动注册有限的几个本地方法，都在 RegisterCenter 的 init 方法中手动注册，并在我们的 JVM 开启时，手动调用该方法，即完成了注册。已下就是我的 JVM 中所有实现的本地方法，如果各位感兴趣，可以继续向 init 方法中添加对应的注册。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//对外供 JVM 启动后的唯一接入口，JVM 启动后应该立即调用 RegisterCenter 的 init 方法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    register(<span class="string">"java/lang/Object"</span>, <span class="string">"getClass"</span>, <span class="string">"()Ljava/lang/Class;"</span>, <span class="keyword">new</span> Nobject.getClass());</span><br><span class="line">    register(<span class="string">"java/lang/Class"</span>, <span class="string">"getPrimitiveClass"</span>, <span class="string">"(Ljava/lang/String;)Ljava/lang/Class;"</span>, <span class="keyword">new</span> Nclass.getPrimitiveClass());</span><br><span class="line">    register(<span class="string">"java/lang/Class"</span>, <span class="string">"getName0"</span>, <span class="string">"()Ljava/lang/String;"</span>, <span class="keyword">new</span> Nclass.getName0());</span><br><span class="line">    register(<span class="string">"java/lang/Class"</span>, <span class="string">"desiredAssertionStatus0"</span>, <span class="string">"(Ljava/lang/Class;)Z"</span>, <span class="keyword">new</span> Nclass.desiredAssertionStatus0());</span><br><span class="line">    register(<span class="string">"java/lang/Class"</span>, <span class="string">"isArray"</span>, <span class="string">"()Z"</span>, <span class="keyword">new</span> Nclass.isArray());</span><br><span class="line">    register(<span class="string">"java/lang/Throwable"</span>, <span class="string">"fillInStackTrace"</span>, <span class="string">"(I)Ljava/lang/Throwable;"</span>, <span class="keyword">new</span> Nthrowable.fillInStackTrace());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="为本地方法注入字节码"><a href="#为本地方法注入字节码" class="headerlink" title="为本地方法注入字节码"></a>为本地方法注入字节码</h1><p>上面只是完成了本地方法的注册，接下来就要实现本地方法的执行过程了。但是在实现本地方法之前，我们还要对本地方法进行特殊的处理，因为在 JVM 中并没有规定如何实现和调用本地方法。在 JVM 中调用 native 方法和调用其它方法所用的指令是一样的，也就是说调用本地静态方法会产生一个<code>invoke_static</code>的指令，调用本地非静态方法，会产生一个<code>invoke_special</code>的指令。但是我们对于本地方法，我们要做特殊的处理，因为 <strong>native 方法在 class 文件中没有字节码。</strong> </p>
<p>以静态普通方法和静态本地方法的指令为例，JVM 都是产生的 invoke_static 的指令，其指令的指令过程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">INVOKE_STATIC</span> <span class="keyword">extends</span> <span class="title">Index16Instruction</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        RuntimeConstantPool runtimeConstantPool = frame.getMethod().getClazz().getRuntimeConstantPool();</span><br><span class="line">        <span class="comment">//通过 index,拿到方法符号引用</span></span><br><span class="line">        MethodRef methodRef = (MethodRef) runtimeConstantPool.getRuntimeConstant(index).getValue();</span><br><span class="line">        Zmethod resolvedMethod = methodRef.resolvedMethod();</span><br><span class="line">        <span class="keyword">if</span> (!resolvedMethod.isStatic()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IncompatibleClassChangeError();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Zclass clazz = resolvedMethod.getClazz();</span><br><span class="line">        <span class="comment">//判断其 Class 是否已经加载过,如果还未加载,那么调用其类的&lt;clinit&gt;方法压栈</span></span><br><span class="line">        <span class="keyword">if</span> (!clazz.isInitStarted()) &#123;</span><br><span class="line">            <span class="comment">//当前指令已经是在执行 new 了,但是类还没有加载,所以当前帧先回退,让类初始化的帧入栈,等类初始化完成后,重新执行 new;</span></span><br><span class="line">            frame.revertNextPC();</span><br><span class="line">            ClassInitLogic.initClass(frame.getThread(), clazz);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        MethodInvokeLogic.invokeMethod(frame, resolvedMethod);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodInvokeLogic</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeMethod</span><span class="params">(Zframe invokerFrame, Zmethod method)</span> </span>&#123;</span><br><span class="line">        Zthread thread = invokerFrame.getThread();</span><br><span class="line">        Zframe newFrame = thread.createFrame(method);</span><br><span class="line">        thread.pushFrame(newFrame);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> argSlotCount = method.getArgSlotCount();</span><br><span class="line">        <span class="keyword">if</span> (argSlotCount &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = argSlotCount - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">                Slot slot = invokerFrame.getOperandStack().popSlot();</span><br><span class="line">                newFrame.getLocalVars().setSlot(i, slot);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 invoke_static 指令中，解析方法符号引用为直接引用，然后就会调用<code>MethodInvokeLogic.invokeMethod(frame, resolvedMethod)</code>方法，该方法内部会创建一个新的 frame 来供被调用的方法来执行，此时 JVM 的栈帧的顶部就是该 frame，解释器此时会读取 JVM 栈帧顶部的 frame 作为当前 frame，并执行该 frame 所绑定的 method 中的字节码。因为本地方法没有字节码，但我们又要让本地方法也适应 JVM 解释器，因此我们的做法是为本地方法注入字节码，本地方法的字节码只需要两个字节，第一个字节用来表示接下来要执行的方法是本地方法，(JVM 规范中预留了两条指令，操作码为 0xFE 和 0xFF，这里我们使用 0xFE 来表示本地方法的调用)。第二个字节用来表示本地方法的 return 指令，其 return 指令和非 native 方法的 return 指令完全一样。</p>
<p>接下来先完成本地方法字节码的构造，在创建 Zmethod 实例时，如果该方法是 native 的，我们将进行如下构造：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">Zmethod</span><span class="params">(Zclass clazz, MemberInfo classFileMethod)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(clazz, classFileMethod);</span><br><span class="line">    copyAttributes(classFileMethod);</span><br><span class="line">    parsedDescriptor = <span class="keyword">new</span> MethodDescriptor(<span class="keyword">this</span>.descriptor);</span><br><span class="line">    argSlotCount = calcArgSlotCount(parsedDescriptor.getParameterTypes());</span><br><span class="line">    <span class="keyword">if</span> (isNative()) &#123;</span><br><span class="line">        injectCodeAttribute(parsedDescriptor.getReturnType());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// JVM 并没有规定如何实现和调用本地方法，这里我们依然使用 JVM 栈 来执行本地方法</span></span><br><span class="line"><span class="comment">// 但是本地方法中并不包含字节码，那么本地方法的调用，这里我们利用接口来实现调用对应的方法；</span></span><br><span class="line"><span class="comment">// 同时 JVM 中预留了两条指令，操作码分别是 0xff 和 0xfe，下面使用 0xfe 来当前方法为表示本地方法</span></span><br><span class="line"><span class="comment">// 第二个字节为本地方法的返回指令，该指令和普通方法的返回指令是一样的。</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">injectCodeAttribute</span><span class="params">(String returnType)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//本地方法的操作数栈暂时为 4;至少能容纳返回值</span></span><br><span class="line">    <span class="keyword">this</span>.maxStack = <span class="number">4</span>;</span><br><span class="line">    <span class="comment">//本地方法的局部变量表只用来存放参数,因此直接这样赋值</span></span><br><span class="line">    <span class="keyword">this</span>.maxLocals = <span class="keyword">this</span>.argSlotCount;</span><br><span class="line">    <span class="comment">//接下来为本地方法构造字节码:起始第一个字节都是 0xfe,用来表用这是本地方法;</span></span><br><span class="line">    <span class="comment">//第二个字节码则根据不同的返回值类型选择相应的 xreturn 的指令即可</span></span><br><span class="line">    <span class="comment">//不必担心下面的 byte 的强转，因为在读取字节码时，使用的是 readUint8()方法</span></span><br><span class="line">    <span class="keyword">switch</span> (returnType.charAt(<span class="number">0</span>)) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'V'</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xb1</span>&#125;; <span class="comment">// return</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'L'</span>:</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'['</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xb0</span>&#125;; <span class="comment">// areturn</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'D'</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xaf</span>&#125;; <span class="comment">// dreturn</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'F'</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xae</span>&#125;; <span class="comment">// freturn</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'J'</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xad</span>&#125;; <span class="comment">// lreturn</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">this</span>.code = <span class="keyword">new</span> <span class="keyword">byte</span>[]&#123;(<span class="keyword">byte</span>) <span class="number">0xfe</span>, (<span class="keyword">byte</span>) <span class="number">0xac</span>&#125;;<span class="comment">// ireturn</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意在上面的字节注入中，还未本地方法添加了本地变量表和操作数栈。本地变量表的大小为本地方法的参数个数。操作数栈的大小这里设置为 4，其实这个值至少是 2，因为我们只是用操作数栈来盛放本地方法的返回值。</p>
<h1 id="本地方法的调用"><a href="#本地方法的调用" class="headerlink" title="本地方法的调用"></a>本地方法的调用</h1><p>在完成了本地方法的字节注入之后，终于可以实现本地方法的调用了。因为我们为本地方法注入了两个字节码，所以在 JVM 的解释器真正执行本地方法时，会本地方法中的这两个字节码，首先是 0xFE，这是我们自己构造的，解释器在遇到这个字节码时，其实是不认识的，因为 JVM 规范中没有用到该字节码，于是在这里我们手动创建一个 invoke_native 指令，该指令就对应 0xFE。不要忘了在我们的 InstructionFactory.java 的 createInstruction 方法中，添加对该字节码的解析。注意：JVM 中是没有 invoke_native 指令的，这是我们自己创建的指令。其具体实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">INVOKE_NATIVE</span> <span class="keyword">extends</span> <span class="title">NoOperandsInstruction</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        Zmethod method = frame.getMethod();</span><br><span class="line">        String clazzName = method.getClazz().thisClassName;</span><br><span class="line">        String methodName = method.getName();</span><br><span class="line">        String descriptor = method.getDescriptor();</span><br><span class="line"></span><br><span class="line">        NativeMethod nativeMethod = RegisterCenter.findNativeMethod(clazzName, methodName, descriptor);</span><br><span class="line">        <span class="keyword">if</span> (nativeMethod == <span class="keyword">null</span>) &#123;</span><br><span class="line">            String methodInfo = clazzName + <span class="string">"."</span> + methodName + descriptor;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UnsatisfiedLinkError(methodInfo);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        nativeMethod.run(frame);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面也说了本地方法中没有字节码，我们认为注入了标示本地方法开始的字节码 0xFE，已经本地方法返回的字节码。但是中间具体的指令流程我们是无法用字节码构造了，因为这样太麻烦了。所以在 java 层面是不知道本地方法内部如何执行，因为本地方法会映射到 JVM 中的一个 c 的指针，也就是说每一个本地方法对应的具体实现都已经在 JVM 中实现好了，由该指针指向的代码来执行具体的逻辑(我们的 JVM 中就是通过接口来模拟方法指针了)。这就需要在 JVM 找到对应的本地方法的具体实现，并执行本地方法。</p>
<p>本地方法的查找，也很简单，只要从本地方法注册表中根据方法名获取到具体实现即可，我们这里是获取到 NativeMethod 接口的一个实现类，然后调用其 run 方法。这里要注意的是如果方法名为 registerNatives,则返回一个空实现即可，原因在文章开始已经解释过了。对于其它情况，如果在本地方法表中没有提前注册，那么将抛出 UnsatisfiedLinkError 的错误。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> NativeMethod <span class="title">findNativeMethod</span><span class="params">(String className, String methodName, String methodDescriptor)</span> </span>&#123;</span><br><span class="line">    String key = className + <span class="string">"~"</span> + methodName + <span class="string">"~"</span> + methodDescriptor;</span><br><span class="line">    <span class="keyword">if</span> (nativeMethods.containsKey(key)) &#123;</span><br><span class="line">        <span class="keyword">return</span> nativeMethods.get(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="string">"()V"</span>.equals(methodDescriptor)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">"registerNatives"</span>.equals(methodName)) &#123;</span><br><span class="line">            <span class="comment">//返回一个空的方法执行体 emptyNativeMethod</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> NativeMethod() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="本地方法调用实战"><a href="#本地方法调用实战" class="headerlink" title="本地方法调用实战"></a>本地方法调用实战</h1><p>通过上面的讲解，可能还是一头雾水，请不要怀疑自己的能力，是我表达的不太够准确，因此在最后一节，准备了一个本地方法调用的实战，当你看明白了这个实战的流程之后，再看上面的讲解，也许你会豁然开朗。</p>
<p>本实战准备的例子是<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/test/TestGetClass11.java" target="_blank" rel="noopener">TestGetClass11.java</a><br>测试所用的方法是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    String s1 = <span class="keyword">int</span>.class.getName();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里是调用了基本类型的类，<a href="https://zachaxy.github.io/2018/01/18/%E6%89%8B%E5%86%99JVM%E7%B3%BB%E5%88%97-16-%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6%E7%AE%80%E4%BB%8B/">上一章</a>反射中已经介绍了其实现原理，我们这里重点看 getName 方法，该方法内步流程是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    String name = <span class="keyword">this</span>.name;</span><br><span class="line">    <span class="keyword">if</span> (name == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">this</span>.name = name = getName0();</span><br><span class="line">    <span class="keyword">return</span> name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">native</span> String <span class="title">getName0</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>

<p>发现这里调用了 getName0 方法，而 getName0 方法就是本地方法。所以我们要在 JVM 中实现该方法。在 znative 包下，创建 Nclass.java，在 java/lang/Class 中的本地方法都将在 Nclass 中进行实现。不过我们并不打算将 Class 中的本地方法全部实现，这里只用到了 getName0 的方法，所以我们只实现 getName0 的逻辑，其具体实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">getName0</span> <span class="keyword">implements</span> <span class="title">NativeMethod</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">(Zframe frame)</span> </span>&#123;</span><br><span class="line">        Zobject self = frame.getLocalVars().getRef(<span class="number">0</span>);</span><br><span class="line">        Zclass clazz = (Zclass) self.extra;</span><br><span class="line">        String name = clazz.getJavaName();</span><br><span class="line">        Zobject nameObj = StringPool.jString(clazz.getLoader(), name);</span><br><span class="line">        frame.getOperandStack().pushRef(nameObj);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 JVM 本地方法 getName0 实现了 NativeMethod 接口，在 run 方法中，首先获取本地变量表中的第一个变量，也就是调用 getName0 方法的对象 <code>this</code>，然后获取到 this 的类，最核心就是 <code>class.getJavaName()</code>这一句，获取到当前 class 的 javaName，其实现也非常简单，在 Zclass.java 中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getJavaName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> thisClassName.replace(<span class="string">"/"</span>, <span class="string">"."</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有了本地方法的具体实现，接下来记得在本地方法注册表中进行注册，其在 RegisterCenter.java 的 init 方法中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	...</span><br><span class="line">	register(<span class="string">"java/lang/Class"</span>, <span class="string">"getName0"</span>, <span class="string">"()Ljava/lang/String;"</span>, <span class="keyword">new</span> Nclass.getName0());</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后不要忘记在 JVM 启动之前，调用<code>RegisterCenter.init()</code>，将本地方法注册到 JVM 中。具体实现流程请参考<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/test/TestGetClass11.java" target="_blank" rel="noopener">TestGetClass11.java</a></p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2018/01/18/手写JVM系列-17-本地方法的调用过程/" title="手写JVM系列(17)本地方法的调用过程">https://zachaxy.github.io/2018/01/18/手写JVM系列-17-本地方法的调用过程/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2018/01/18/手写JVM系列-16-反射机制简介/" rel="next" title="手写JVM系列(16)反射机制简介">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(16)反射机制简介
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/01/20/手写JVM系列-18-异常处理机制/" rel="prev" title="手写JVM系列(18)异常处理机制">
                手写JVM系列(18)异常处理机制 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#本地方法的注册"><span class="nav-number">1.</span> <span class="nav-text">本地方法的注册</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#本地方法注册的时机"><span class="nav-number">2.</span> <span class="nav-text">本地方法注册的时机</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#为本地方法注入字节码"><span class="nav-number">3.</span> <span class="nav-text">为本地方法注入字节码</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#本地方法的调用"><span class="nav-number">4.</span> <span class="nav-text">本地方法的调用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#本地方法调用实战"><span class="nav-number">5.</span> <span class="nav-text">本地方法调用实战</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
